<template>
	<view class="product-upload-page">
		<!-- 导航栏：标题根据状态动态显示（新建/编辑/重新审核） -->
		<view class="navbar" :style="{ paddingTop: navBarTop + 'rpx' }">
			<view class="nav-left" @click="navigateBack">
				<uni-icons type="arrow-left" size="28" color="#333"></uni-icons>
			</view>
			<view class="nav-title">
				{{ getPageTitle() }}
			</view>
			<view class="nav-right" @click="gotoDraftList">
				<text class="draft-text">草稿</text>
			</view>
		</view>

		<!-- 主内容区：保持原表单结构，新增状态提示（如“待审核商品编辑后需重新提交审核”） -->
		<scroll-view class="content" scroll-y :style="{ paddingTop: navBarTop + 88 + 'rpx' }">
			<!-- 状态提示条：仅当编辑“待审核/已上架”商品时显示 -->
			<view class="status-tip" v-if="showStatusTip">
				<uni-icons type="info" size="20" color="#ff9500"></uni-icons>
				<text class="tip-text">{{ getStatusTipText() }}</text>
			</view>

			<form @submit="submitForm" ref="productForm">
				<!-- 商品基本信息（保持不变） -->
				<view class="form-section">
					<view class="form-item">
						<view class="form-label required">商品名称</view>
						<view class="form-input">
							<input type="text" v-model="product.productName" placeholder="请输入商品名称" required />
						</view>
					</view>
					<view class="sell-type">
						<radio-group name="" @change="sellType" style="gap: 50rpx">
							<label style="margin-right: 50rpx">
								<radio value="onshop" style="transform: scale(0.7)" :checked="true" />
								<text>上架商城</text>
							</label>
							<label>
								<radio value="self" style="transform: scale(0.7)" />
								<text>自行销售</text>
							</label>
						</radio-group>
					</view>
					<!-- 分类选择、规格、单位、价格、库存、标签（均保持不变） -->
					<view class="form-item">
						<view class="form-label required">商品分类</view>
						<view class="form-input">
							<picker
								mode="multiSelector"
								:range="categoryRange"
								:value="categoryIndex"
								range-key="label"
								@change="onCategoryChange"
								@columnchange="onCategoryColumnChange"
							>
								<view class="picker-view">
									{{
										categoryIndex[0] >= 0 && categoryIndex[1] >= 0 && categoryRange[0][categoryIndex[0]] && categoryRange[1][categoryIndex[1]]
											? categoryRange[0][categoryIndex[0]].label + ' / ' + categoryRange[1][categoryIndex[1]].label
											: '请选择商品分类'
									}}
								</view>
							</picker>
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">规格说明</view>
						<view class="form-input">
							<input type="text" v-model="product.specs" placeholder="请输入商品规格（如：颜色、尺寸等）" />
						</view>
					</view>
					<view class="form-item">
						<view class="form-label required">单位</view>
						<view class="form-input">
							<input type="text" v-model="product.unit" placeholder="如：个、件、kg等" required />
						</view>
					</view>
					<view class="form-item">
						<view class="form-label required">售价</view>
						<view class="form-input price-input">
							<text class="rmb-sign">¥</text>
							<input type="number" v-model="product.price" placeholder="0.00" step="0.01" required />
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">原价</view>
						<view class="form-input price-input">
							<text class="rmb-sign">¥</text>
							<input type="number" v-model="product.originalPrice" placeholder="0.00" step="0.01" />
						</view>
					</view>
					<view class="form-item">
						<view class="form-label required">库存</view>
						<view class="form-input">
							<input type="number" v-model="product.stock" placeholder="0" min="0" required />
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">标签</view>
						<view class="form-input">
							<input type="text" v-model="product.tag" placeholder="如：热销、新品等（多个标签用逗号分隔）" />
						</view>
					</view>
				</view>

				<!-- 商品图片上传、条形码、日期、描述、位置（均保持不变） -->
				<view class="form-section">
					<view class="section-title">商品图片</view>
					<view class="upload-area">
						<view class="upload-item add-upload" @click="chooseImage" v-if="product.images.length < 5">
							<uni-icons type="plus" size="36" color="#999"></uni-icons>
							<text class="upload-text">添加图片</text>
						</view>
						<view class="upload-item" v-for="(img, index) in product.images" :key="index">
							<image :src="img.url" mode="aspectFill" class="upload-img"></image>
							<view class="delete-img" @click="deleteImage(index)">
								<uni-icons type="close" size="20" color="#fff"></uni-icons>
							</view>
						</view>
					</view>
					<view class="upload-tip">最多上传5张图片，第一张为封面图</view>
				</view>
				<view class="form-section">
					<view class="section-title">条形码/二维码(选填)</view>
					<view class="barcode-area">
						<view class="barcode-input">
							<input type="text" v-model="barcodeText" placeholder="输入条形码/二维码内容" />
							<button class="add-btn" @click="addBarcode">添加</button>
						</view>
						<view class="barcode-list">
							<view class="barcode-item" v-for="(code, index) in product.barcode" :key="index">
								<text>{{ code }}</text>
								<uni-icons type="trash" size="20" color="#ff3d00" @click="deleteBarcode(index)"></uni-icons>
							</view>
						</view>
						<button class="scan-btn" @click="scanBarcode">
							<uni-icons type="scan" size="20" color="#fff"></uni-icons>
							<text>扫码添加</text>
						</button>
					</view>
				</view>
				<view class="form-section">
					<view class="form-item">
						<view class="form-label">开始日期</view>
						<view class="form-input">
							<picker mode="date" :value="product.startDate" start="1970-01-01" @change="onStartDateChange">
								<view class="picker-view">{{ product.startDate || '请选择开始日期' }}</view>
							</picker>
						</view>
					</view>
					<view class="form-item">
						<view class="form-label">结束日期</view>
						<view class="form-input">
							<picker mode="date" :value="product.endDate" start="1970-01-01" @change="onEndDateChange">
								<view class="picker-view">{{ product.endDate || '请选择结束日期' }}</view>
							</picker>
						</view>
					</view>
				</view>
				<view class="form-section">
					<view class="form-label vertical-label required">商品描述</view>
					<textarea v-model="product.description" placeholder="请输入商品详细描述..." class="product-desc" rows="6" required></textarea>
				</view>
				<view class="form-section">
					<view class="form-item">
						<view class="form-label">位置信息</view>
						<view class="form-input location-input" @click="chooseLocation">
							<uni-icons type="map" size="22" color="#007aff"></uni-icons>
							<text class="location-text">{{ locationText || '点击选择位置' }}</text>
							<uni-icons type="right" size="18" color="#999"></uni-icons>
						</view>
					</view>
				</view>

				<!-- 提交按钮：根据商品状态动态显示按钮文本（申请上架/重新提交审核） -->
				<view class="submit-area">
					<button class="draft-btn" @click.stop="submitForm('draft')">暂存草稿</button>
					<button class="submit-btn" @click.stop="submitForm('publish')" :loading="submitting" :disabled="submitting">
						{{ getSubmitBtnText() }}
					</button>
				</view>
			</form>
		</scroll-view>
	</view>
</template>

<script>
const db = uniCloud.database();
const _ = db.command;
import setToTarget from '@/utils/setTarget'
import MessageSender from '@/utils/MessageSender.js';
export default {
	data() {
		return {
			navBarTop: 0,
			product: {
				productName: '',
				categorize: '',
				subCategorize: '',
				specs: '',
				unit: '',
				price: '',
				originalPrice: '',
				stock: 0,
				description: '',
				tag: '',
				onShop: false,
				barcode: [],
				images: [], // [{fileID: 'xxx', url: 'xxx'}]
				startDate: '',
				endDate: '',
				location: {},
				// 核心：新增商品状态字段（关联sendgood表状态）
				_id: '', // 草稿表ID
				draftId: '', // 草稿唯一标识
				relatedGoodsId: '', // 关联的正式商品ID（sendgood表）
				goodsStatus: 'draft', // 商品状态（draft/pending/online/offline）
				createTime: 0,
				updateTime: 0
			},
			categoryRange: [[], []],
			categoryIndex: [0, 0],
			allCategories: [],
			barcodeText: '',
			locationText: '',
			submitting: false,
			source: '',
			currentId: ''
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg || {};
		},
		// 是否显示状态提示条（编辑待审核/已上架商品时显示）
		showStatusTip() {
			return ['pending', 'online'].includes(this.product.goodsStatus);
		}
	},
	watch: {
		'product.onShop': {
			handler(newval) {
				(this.categoryRange = [[], []]), (this.allCategories = []), this.getcategory(newval);
			},
			deep: true,
			immediate: true
		}
	},
	async onLoad(options) {
		// await this.getcategory();
		this.setNavBarTop();

		// 接收来源和ID
		this.source = options.source || '';
		this.currentId = options.id || '';

		if (!this.source || !this.currentId) {
			uni.showToast({ title: '新增商品', icon: 'none' });
		}

		// 根据来源加载数据
		if (this.source === 'draft') {
			await this.loadFromDraft(this.currentId); // 从草稿表加载
		} else if (this.source === 'goods') {
			await this.loadFromGoods(this.currentId); // 从正式商品表加载
		}
	},
	methods: {
		// 设置导航栏高度（不变）
		setNavBarTop() {
			try {
				const res = this.storeData.systemInfo;
				this.navBarTop = res.safeArea.top * (750 / res.windowWidth);
			} catch (e) {
				this.navBarTop = 0;
			}
		},

		/**
		 * 核心修改1：加载草稿+关联的正式商品数据（双表关联）
		 * 1. 先查草稿表，获取草稿基本信息
		 * 2. 若有relatedGoodsId，查sendgood表获取商品状态
		 */
		async loadFromDraft(draftId) {
			try {
				this.submitting = true;
				const userId = this.storeData.user?.userId;
				if (!userId) throw new Error('未获取到用户信息');

				const draftRes = await db.collection('productDraft').where({ draftId, senderUserId: userId }).get();
				const draftList = draftRes.result?.data || [];
				if (draftList.length === 0) throw new Error('草稿不存在或已删除');
				const draft = draftList[0];

				// 同步正式商品状态（如果有关联）
				let goodsStatus = 'draft';
				if (draft.relatedGoodsId) {
					const goodsRes = await db.collection('sendgood').where({ _id: draft.relatedGoodsId, senderUserId: userId }).get();
					const goodsList = goodsRes.result?.data || [];
					if (goodsList.length > 0) {
						goodsStatus = goodsList[0].status;
					}
				}

				// 回显数据
				this.product = {
					...draft,
					goodsStatus,
					images: (draft.images || []).map((img) => (img.fileID && img.url ? img : { fileID: '', url: '/static/images/default-goods.png' }))
				};
				this.locationText = draft.location?.name || draft.location?.address || '';
				this.setCategoryIndex(draft.categorize, draft.subCategorize);
			} catch (error) {
				console.error('加载草稿失败:', error);
				uni.showToast({ title: error.message || '加载失败', icon: 'none' });
				uni.navigateBack();
			} finally {
				this.submitting = false;
			}
		},
		/**
		 * 新增：从正式商品表加载数据（即使没有草稿也能编辑）
		 */
		async loadFromGoods(goodsId) {
			try {
				this.submitting = true;
				const userId = this.storeData.user?.userId;
				if (!userId) throw new Error('未获取到用户信息');

				// 1. 先加载正式商品数据
				const goodsRes = await db.collection('sendgood').where({ _id: goodsId, senderUserId: userId }).get();
				const goodsList = goodsRes.result?.data || [];
				if (goodsList.length === 0) throw new Error('商品不存在或已删除');
				const goods = goodsList[0];

				// 2. 检查是否有对应的草稿（通过relatedGoodsId关联）
				let draft = null;
				const draftRes = await db.collection('productDraft').where({ relatedGoodsId: goodsId, senderUserId: userId }).get();
				const draftList = draftRes.result?.data || [];
				if (draftList.length > 0) {
					draft = draftList[0]; // 有草稿：优先用草稿数据（最新编辑内容）
				}

				// 3. 回显数据（优先用草稿，无草稿则用正式商品数据）
				const baseData = draft || goods;
				this.product = {
					...baseData,
					_id: draft?._id || '', // 草稿ID（若无则为空）
					draftId: draft?.draftId || `${Date.now()}-${Math.floor(Math.random() * 1000)}`, // 自动生成草稿ID
					relatedGoodsId: goodsId, // 关联正式商品ID
					goodsStatus: goods.status, // 状态取自正式商品
					images: (baseData.images || []).map((img) => (img.fileID && img.url ? img : { fileID: '', url: '/static/images/default-goods.png' }))
				};
				this.locationText = baseData.location?.name || baseData.location?.address || '';
				this.setCategoryIndex(baseData.categorize, baseData.subCategorize);
			} catch (error) {
				console.error('加载商品失败:', error);
				uni.showToast({ title: error.message || '加载失败', icon: 'none' });
				uni.navigateBack();
			} finally {
				this.submitting = false;
			}
		},

		// async loadDraftAndGoodsData(draftId) {
		// 	console.log(draftId);
		// 	try {
		// 		this.submitting = true;
		// 		const userId = this.storeData.user?.userId;
		// 		if (!userId) throw new Error('未获取到用户信息');

		// 		// 1. 查草稿表
		// 		const draftRes = await db.collection('productDraft')
		// 			.where({ draftId:draftId, senderUserId: userId })
		// 			.get();
		// 			console.log('draftRes',draftRes);
		// 		const draftList = draftRes.result?.data || [];
		// 		if (draftList.length === 0) throw new Error('草稿不存在或已删除');
		// 		const draft = draftList[0];

		// 		// 2. 若有关联的正式商品ID，查sendgood表获取商品状态
		// 		let goodsStatus = 'draft';
		// 		if (draft.relatedGoodsId) {
		// 			const goodsRes = await db.collection('sendgood')
		// 				.where({ _id: draft.relatedGoodsId, senderUserId: userId })
		// 				.get();
		// 			const goodsList =  goodsRes.result?.data || [];
		// 			if (goodsList.length > 0) {
		// 				goodsStatus = goodsList[0].status; // 同步正式商品状态
		// 			}
		// 		}

		// 		// 3. 回显数据（含商品状态）
		// 		this.product = {
		// 			...draft,
		// 			goodsStatus: goodsStatus, // 关键：保存商品状态
		// 			images: (draft.images || []).map(img =>
		// 				(img.fileID && img.url) ? img : { fileID: '', url: '/static/images/default-goods.png' }
		// 			)
		// 		};
		// 		this.locationText = draft.location?.name || draft.location?.address || '';
		// 		this.setCategoryIndex(draft.categorize, draft.subCategorize);

		// 	} catch (error) {
		// 		console.error('加载数据失败:', error);
		// 		uni.showToast({ title: error.message || '数据加载失败', icon: 'none' });
		// 		uni.navigateBack();
		// 	} finally {
		// 		this.submitting = false;
		// 	}
		// },
		sellType(e) {
			console.log(e);
			if (e.detail.value === 'onshop') {
				this.product.onShop = true;
			} else if (e.detail.value === 'self') {
				this.product.onShop = false;
			}
		},

		// 分类回显（不变）
		setCategoryIndex(cateId, subCateId) {
			if (!this.allCategories.length) return;
			const firstIndex = this.allCategories.findIndex((cate) => cate.id === cateId);
			if (firstIndex === -1) return;
			const subCates = this.allCategories[firstIndex].subCategory || [];
			const secondIndex = subCates.findIndex((sub) => sub.id === subCateId);
			this.categoryIndex = [firstIndex, secondIndex >= 0 ? secondIndex : 0];
			this.categoryRange[1] = subCates.map((sub) => ({ label: sub.name, value: sub.id }));
		},

		// 返回上一页（不变）
		navigateBack() {
			uni.navigateBack({ delta: 1 });
		},

		// 跳转到草稿列表（不变）
		gotoDraftList() {
			uni.navigateTo({ url: '/pages/draft/draft' });
		},

		// 获取分类（不变，兼容默认分类复制）
		async getcategory(onShop) {
			try {
				const userId = this.storeData.user?.userId;
				if (!userId) throw new Error('未获取到用户信息');

				let res = await db.collection('category').where({ userId }).get();
				console.log('分类.....', res);
				//当需要上架商城时无自已分类才复制系统公共分类
				if (res.result?.data.length === 0 && onShop) {
					// 复制默认用户分类
					const defaultRes = await db.collection('category').where({ userId: 'system' }).get();
					const defaultCate = defaultRes.result?.data[0];
					if (!defaultCate?.category) throw new Error('默认分类数据不存在');

					await db.collection('category').add({ userId, category: defaultCate.category });
					res = await db.collection('category').where({ userId }).get();
				}

				const cateData = res.result?.data[0];
				if (cateData?.category) {
					this.allCategories = cateData.category;
					this.categoryRange = this.formatPickerData(this.allCategories);
				} else {
					throw new Error('未获取到分类数据');
				}
			} catch (error) {
				console.error('获取分类失败:', error);
				uni.showToast({ title: error.message || '分类加载失败', icon: 'none' });
			}
		},

		// 格式化分类数据（不变）
		formatPickerData(categories) {
			if (!categories?.length) return [[], []];
			const firstColumn = categories.map((cate) => ({
				label: cate.name,
				value: cate.id,
				subCates: cate.subCategory || []
			}));
			const secondColumn = firstColumn[0]?.subCates.map((sub) => ({ label: sub.name, value: sub.id })) || [];
			return [firstColumn, secondColumn];
		},

		// 分类选择变化、列联动、选择图片、删除图片、条形码、日期、位置（均保持不变）
		onCategoryChange(e) {
			this.categoryIndex = e.detail.value;
			const firstCate = this.categoryRange[0][this.categoryIndex[0]];
			const secondCate = this.categoryRange[1][this.categoryIndex[1]];
			if (firstCate && secondCate) {
				this.product.categorize = firstCate.value;
				this.product.subCategorize = secondCate.value;
			}
		},
		onCategoryColumnChange(e) {
			const { column, value } = e.detail;
			if (column === 0) {
				const selectedCate = this.categoryRange[0][value];
				if (selectedCate?.subCates) {
					this.categoryRange[1] = selectedCate.subCates.map((sub) => ({ label: sub.name, value: sub.id }));
					this.categoryIndex = [value, 0];
				}
			}
		},
		chooseImage() {
			uni.chooseImage({
				count: 5 - this.product.images.length,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					res.tempFilePaths.forEach((path) => {
						this.product.images.push({ url: path, fileID: null });
					});
				}
			});
		},
		deleteImage(index) {
			this.product.images.splice(index, 1);
		},
		addBarcode() {
			if (!this.barcodeText.trim()) return;
			this.product.barcode.push(this.barcodeText.trim());
			this.barcodeText = '';
		},
		deleteBarcode(index) {
			this.product.barcode.splice(index, 1);
		},
		scanBarcode() {
			uni.scanCode({
				success: (res) => this.product.barcode.push(res.result),
				fail: () => uni.showToast({ title: '扫码失败', icon: 'none' })
			});
		},
		onStartDateChange(e) {
			this.product.startDate = e.detail.value;
		},
		onEndDateChange(e) {
			this.product.endDate = e.detail.value;
		},
		chooseLocation() {
			uni.chooseLocation({
				useSecureNetwork: true,
				success: (res) => {
					this.product.location = { name: res.name, address: res.address, latitude: res.latitude, longitude: res.longitude };
					this.locationText = res.name || res.address;
				}
			});
		},
	

	/**
	 * 核心修改2：动态页面标题（根据状态区分）
	 * - 新建草稿：商品上架
	 * - 编辑草稿：编辑草稿
	 * - 编辑待审核/已上架商品：编辑商品（重新审核）
	 */
	getPageTitle() {
		if (!this.product.draftId) return '商品新建'; // 新建

		if (this.product.goodsStatus === 'draft') return '编辑草稿'; // 编辑纯草稿
		return '编辑商品（重新审核）'; // 编辑待审核/已上架商品
	},

	/**
	 * 核心修改3：动态状态提示文本（编辑待审核/已上架商品时）
	 */
	getStatusTipText() {
		if (this.product.goodsStatus === 'pending') {
			return '当前商品处于待审核状态，编辑后需重新提交审核';
		}
		if (this.product.goodsStatus === 'online') {
			return '当前商品处于已上架状态，编辑后需重新提交审核，审核期间商品将暂时下架';
		}
		return '';
	},

	/**
	 * 核心修改4：动态提交按钮文本（根据状态区分）
	 * - 纯草稿：申请上架
	 * - 待审核/已上架商品：重新提交审核
	 */
	getSubmitBtnText() {
		if (this.product.goodsStatus === 'draft' && this.product.onShop) return '申请上架';
		if (this.product.goodsStatus === 'draft' && !this.product.onShop) return '发布商品';
		return '重新提交审核';
	},

	// 表单验证（不变）
	validateForm() {
		if (!this.product.productName.trim()) return { valid: false, msg: '请输入商品名称' };
		if (!this.product.categorize) return { valid: false, msg: '请选择商品分类' };
		if (!this.product.unit.trim()) return { valid: false, msg: '请输入商品单位' };
		if (!this.product.price || isNaN(this.product.price) || this.product.price <= 0) return { valid: false, msg: '请输入有效的售价' };
		if (isNaN(this.product.stock) || this.product.stock < 0) return { valid: false, msg: '请输入有效的库存' };
		if (!this.product.description.trim()) return { valid: false, msg: '请输入商品描述' };
		if (this.product.images.length === 0) return { valid: false, msg: '请至少上传一张商品图片' };
		if (this.product.startDate && this.product.endDate) {
			const start = new Date(this.product.startDate).getTime();
			const end = new Date(this.product.endDate).getTime();
			if (end < start) return { valid: false, msg: '结束日期不能早于开始日期' };
		}
		return { valid: true };
	},

	// 上传所有图片（不变）
	async uploadAllImages() {
		const uploadPromises = this.product.images.map((img, index) => {
			if (img.fileID) return Promise.resolve(img);
			return this.uploadImage(img.url, index);
		});
		await Promise.all(uploadPromises);
	},

	// 上传单张图片（不变）
	uploadImage(tempFilePath, index) {
		return new Promise((resolve, reject) => {
			uniCloud.uploadFile({
				cloudPath: `products/${Date.now()}-${Math.random().toString(36).substr(2, 10)}.png`,
				filePath: tempFilePath,
				success: async (uploadRes) => {
					try {
						const fileRes = await uniCloud.getTempFileURL({ fileList: [uploadRes.fileID] });
						if (!fileRes.fileList[0]?.tempFileURL) throw new Error('获取图片URL失败');
						this.product.images[index] = { fileID: uploadRes.fileID, url: fileRes.fileList[0].tempFileURL };
						resolve(this.product.images[index]);
					} catch (err) {
						reject(err);
					}
				},
				fail: (err) => {
					this.product.images.splice(index, 1);
					reject(new Error(`第${index + 1}张图片上传失败`));
				}
			});
		});
	},

	// 准备提交数据（不变，含双表关联字段）
	getSubmitData(type) {
		const now = new Date().getTime();
		return {
			// 商品基础字段
			productName: this.product.productName.trim(),
			onShop:this.product.onShop,
			categorize: this.product.categorize,
			subCategorize: this.product.subCategorize,
			specs: this.product.specs.trim(),
			unit: this.product.unit.trim(),
			price: Number(this.product.price),
			originalPrice: this.product.originalPrice ? Number(this.product.originalPrice) : null,
			stock: Number(this.product.stock),
			description: this.product.description.trim(),
			tag: this.product.tag.trim(),
			barcode: [...this.product.barcode],
			images: [...this.product.images],
			startDate: this.product.startDate,
			endDate: this.product.endDate,
			location: { ...this.product.location },

			// 双表关联字段
			draftId: this.product.draftId || `${now}-${Math.floor(Math.random() * 1000)}`,
			senderUserId: this.storeData.user?.userId || '',
			relatedGoodsId: this.product.relatedGoodsId || '',
			updateTime: now,
			createTime: this.product.createTime || now
		};
	},

	// 保存到草稿表（不变）
	async saveToOnlineDraft(submitData) {
		if (this.product._id) {
			await db.collection('productDraft').doc(this.product._id).update(submitData);
		} else {
			await db.collection('productDraft').add(submitData);
		}
	},

	/**
	 * 核心修改5：提交到正式商品表（适配多状态流程）
	 * 1. 新增商品：创建sendgood记录，状态设为“待审核”（pending）
	 * 2. 编辑已有商品：更新sendgood记录，状态重置为“待审核”（pending），并保留已售数量
	 */
	async publishToSendgood(submitData) {
		let goodsId = this.product.relatedGoodsId;
		const now = new Date().getTime();
		const goodsData = {
			productName: submitData.productName,
			categorize: submitData.categorize,
			subCategorize: submitData.subCategorize,
			specs: submitData.specs,
			unit: submitData.unit,
			price: submitData.price,
			originalPrice: submitData.originalPrice,
			stock: submitData.stock,
			description: submitData.description,
			tag: submitData.tag,
			barcode: submitData.barcode,
			images: submitData.images,
			startDate: submitData.startDate,
			endDate: submitData.endDate,
			location: submitData.location,
			senderUserId: submitData.senderUserId,
			onShop:submitData.onShop,
			sendTime: goodsId ? submitData.updateTime : now, // 新增用当前时间，编辑保留原发布时间
			status: 'pending', // 关键：无论新增/编辑，提交后均设为“待审核”
			updateTime: now // 新增更新时间字段，用于排序
		};

		if (goodsId) {
			// 编辑已有商品：先查已售数量，避免覆盖
			const goodsRes = await db.collection('sendgood').doc(goodsId).get();
			const goods = goodsRes.data || goodsRes.result?.data?.[0] || {};
			goodsData.saled = goods.saled || 0; // 保留已售数量

			// 更新正式商品表
			await db.collection('sendgood').doc(goodsId).update(goodsData);
		} else {
			// 新增商品：创建正式商品记录
			goodsData.saled = 0; // 初始已售数量为0
			const addRes = await db.collection('sendgood').add(goodsData);
			goodsId = addRes.id || addRes.result?.id; // 兼容新旧版本返回格式
		}

		// 更新草稿表：关联正式商品ID，标记状态（无需在草稿表存status，状态从sendgood同步）
		await db.collection('productDraft').where({ draftId: submitData.draftId }).update({
			relatedGoodsId: goodsId,
			updateTime: now
		});
		return goodsId
		
	},

	// 提交表单（不变，触发草稿/正式商品保存）
	async submitForm(type) {
		let goodId=''
		const validateRes = this.validateForm();
		if (!validateRes.valid) {
			return uni.showToast({ title: validateRes.msg, icon: 'none' });
		}

		this.submitting = true;
		try {
			await this.uploadAllImages();
			const submitData = this.getSubmitData(type);
		

			if (type === 'draft') {
				// 暂存草稿：仅更新草稿表
				await this.saveToOnlineDraft(submitData);
				uni.showToast({ title: '草稿暂存成功' });
				uni.navigateTo({ url: '/pages/draft/draft' });
			} else {
				// 提交审核：更新草稿表+正式商品表
				await this.saveToOnlineDraft(submitData); // 先更新草稿
			const res=	await this.publishToSendgood(submitData); 
			goodId=res
			
							if (this.product.onShop) {
					uni.showToast({ title: '提交审核成功，等待审核' });
					setTimeout(() => uni.navigateTo({ url: '/pages/draft/draft' }), 2000);
				}
			}
			if (type !== 'draft'&&!this.product.onShop) {
				this.$store.commit('msg/SET_queryParam', {
					type: 'public',
					location: this.$store.state.msg.location
				});
				this.$store.commit('msg/SET_location', this.$store.state.msg.location);
				setToTarget('public', { targetName: this.address });
			    const sendmsg=new MessageSender(this.$store.state.msg)
			await sendmsg.sendProduct(this.$store.state.msg.toTarget,goodId) 	
				uni.navigateTo({
					url: '/pages/messages/messages'
				});
			
			}
		} catch (error) {
			console.error(`${type === 'draft' ? '草稿暂存' : '提交审核'}失败:`, error);
			uni.showToast({ title: error.message || '操作失败，请重试', icon: 'none' });
		} finally {
			this.submitting = false;
		}
	}}
	
};
</script>

<style lang="scss" scoped>
/* 原有样式不变，新增状态提示条样式 */
.product-upload-page {
	min-height: 100vh;
	background-color: #f5f5f5;
}
/* 新增：状态提示条 */
.status-tip {
	background-color: #fff8e6;
	color: #ff9500;
	padding: 16rpx 30rpx;
	margin: 0 30rpx 20rpx;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	gap: 10rpx;
}
.tip-text {
	font-size: 26rpx;
}
/* 原有样式（导航栏、表单、上传区等）保持不变 */
.navbar {
	display: flex;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 9999;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	padding: 0 30rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
}
.nav-left,
.nav-right {
	width: 60rpx;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}
.nav-title {
	font-size: 36rpx;
	font-weight: 500;
	color: #333;
	flex: 1;
	text-align: center;
}
.draft-text {
	font-size: 28rpx;
	color: #007aff;
}
.content {
	padding-bottom: 120rpx;
}
.form-section {
	background-color: #fff;
	margin-bottom: 20rpx;
	padding: 0 30rpx;
}
.sell-type {
	width: 100%;
	display: flex;
	align-items: center;
	gap: 50rpx;
	padding: 5rpx;
	font-size: 26rpx;
	font-weight: 600;
	justify-content: space-evenly;
}
/* 其余原有样式均保持不变 */
.section-title {
	font-size: 28rpx;
	color: #666;
	padding: 24rpx 0;
	border-bottom: 1px solid #f5f5f5;
}
.form-item {
	display: flex;
	align-items: center;
	padding: 24rpx 0;
	border-bottom: 1px solid #f5f5f5;
}
.form-label {
	width: 180rpx;
	font-size: 30rpx;
	color: #333;
	padding-right: 20rpx;
	box-sizing: border-box;
}
.required::after {
	content: '*';
	color: #ff3d00;
	margin-left: 6rpx;
}
.vertical-label {
	display: block;
	padding: 24rpx 0 10rpx;
}
.form-input {
	flex: 1;
	position: relative;
}
input,
.picker-view {
	width: 100%;
	font-size: 30rpx;
	color: #333;
	padding: 6rpx 0;
}
input::placeholder {
	color: #ccc;
}
.price-input {
	display: flex;
	align-items: center;
}
.rmb-sign {
	font-size: 30rpx;
	color: #333;
	margin-right: 8rpx;
}
.upload-area {
	display: flex;
	flex-wrap: wrap;
	padding: 20rpx 0;
	gap: 20rpx;
}
.upload-item {
	width: 160rpx;
	height: 160rpx;
	border-radius: 12rpx;
	position: relative;
	overflow: hidden;
}
.add-upload {
	border: 2rpx dashed #ddd;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.upload-text {
	font-size: 24rpx;
	color: #999;
	margin-top: 10rpx;
}
.upload-img {
	width: 100%;
	height: 100%;
	object-fit: cover;
}
.delete-img {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	width: 36rpx;
	height: 36rpx;
	border-radius: 50%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
}
.upload-tip {
	font-size: 24rpx;
	color: #999;
	padding: 0 0 20rpx;
}
.barcode-area {
	padding: 20rpx 0;
}
.barcode-input {
	display: flex;
	gap: 16rpx;
	margin-bottom: 20rpx;
}
.barcode-input input {
	flex: 1;
	border: 1px solid #eee;
	border-radius: 8rpx;
	padding: 0 16rpx;
	height: 70rpx;
	line-height: 70rpx;
}
.add-btn {
	width: 120rpx;
	height: 70rpx;
	line-height: 70rpx;
	text-align: center;
	background-color: #007aff;
	color: #fff;
	font-size: 28rpx;
	border-radius: 8rpx;
	padding: 0;
}
.barcode-list {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
	margin-bottom: 20rpx;
}
.barcode-item {
	display: flex;
	align-items: center;
	gap: 10rpx;
	padding: 10rpx 16rpx;
	background-color: #f5f5f5;
	border-radius: 6rpx;
	font-size: 26rpx;
}
.scan-btn {
	width: 100%;
	height: 70rpx;
	line-height: 70rpx;
	text-align: center;
	background-color: #f5f5f5;
	color: #007aff;
	font-size: 28rpx;
	border-radius: 8rpx;
	padding: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10rpx;
}
.product-desc {
	width: 100%;
	border: 1px solid #eee;
	border-radius: 8rpx;
	padding: 16rpx;
	font-size: 28rpx;
	color: #333;
	min-height: 200rpx;
	margin-bottom: 24rpx;
	box-sizing: border-box;
}
.location-input {
	display: flex;
	align-items: center;
	color: #333;
	font-size: 30rpx;
}
.location-text {
	flex: 1;
	text-align: left;
	padding: 6rpx 0;
	color: #666;
}
.submit-area {
	padding: 30rpx;
	display: flex;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #f5f5f5;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.draft-btn {
	height: 90rpx;
	border-radius: 45rpx;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	background-color: #999;
}
.submit-btn {
	width: 70%;
	height: 90rpx;
	line-height: 90rpx;
	background-color: #ff3d00;
	color: #fff;
	font-size: 32rpx;
	border-radius: 45rpx;
	padding: 0;
}
</style>